package com.reader.cms.utils;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.reader.core.entity.ResultMessageInfo;
import io.swagger.models.auth.In;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 公共使用工具类
 */

public class CommonUtil {

    /**
     * 工具类或是配置文件中直接返回前端异常信息
     * @param request
     * @param response
     * @param success 成功标记，true为成功，false 为失败
     * @param code    消息码
     * @param message 失败消息
     * @throws RuntimeException
     */
    public static void returnResultMessageInfo(HttpServletRequest request,
                                               HttpServletResponse response,
                                               Boolean success,
                                               Integer code,
                                               String message) {
        ResultMessageInfo successResultMessage=new ResultMessageInfo();
        successResultMessage.setCode(code);
        successResultMessage.setMsg(message);
        successResultMessage.setUrl(request.getRequestURI());
        String jsonStr=JSON.toJSONString(successResultMessage);

        try {
            response.setContentType("application/json;charset=utf-8");
            response.addHeader("Access-Control-Allow-origin",request.getHeader("Origin"));
            response.addHeader("Access-Control-Allow-Methods","GET, POST, DELETE, PUT,OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
            response.addHeader("Access-Control-Allow-Credentials","true");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(jsonStr);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 获得token中的信息无需secret解密也能获得
     * @return token中包含的用户名
     */
    public static  String getLoginId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

}
